package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfos;
import cn.stylefeng.guns.sys.core.constant.state.ManagerStatus;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.SaltUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Mt;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.MtYqParam;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.MtYqResult;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtyqParam;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dianping.orderdish.openplatform.BasicResponseModel;
import com.dianping.orderdish.openplatform.client.ApiClient;
import com.dianping.orderdish.openplatform.client.DefaultApiClient;
import com.dianping.orderdish.openplatform.dto.settle.apis.TuangouTradeQueryByPageAPI;
import com.dianping.orderdish.openplatform.dto.settle.request.TradePageQueryRequest;
import com.dianping.orderdish.openplatform.dto.tuangou.OrderSkuDTO;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponCancelAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponMatchConsumeAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponStatusQueryAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.request.CouponCancelRequest;
import com.dianping.orderdish.openplatform.dto.tuangou.request.CouponStatusQueryRequest;
import com.dianping.orderdish.openplatform.dto.tuangou.request.TuangouMatchConsumeRequest;
import com.google.gson.JsonParser;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;

/**
 * 美团验券接口
 */
@CrossOrigin
@Controller
@RequestMapping("/mt")
public class MtController {

    private static Logger logger = LoggerFactory.getLogger(MtController.class);

    @Resource
    private RoleService roleService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BtyMtyqService mtyqService;
    @Autowired
    private AuthService authService;

    //private static final String appKey = "ebf8340f8ba7cb0327173299f689c9d8c664b1f4";
    //private static final String appSecret = "49c6be3b34eb165ccfa0bb167f6799fe6ed81cc2";

    private static final String appKey = "4d0b1d035c651af830ecf9fc32ae69f24dc24ec6";
    private static final String appSecret = "b47f94240f07d06be96167fc0c88f7ededb9ddb0";


    @GetMapping("/userAccess")
    @ResponseBody
    public ResponseData userAccess(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        Map<String, Object> map = new HashMap<>();
        List<String> roleList = new ArrayList<>();
        User users = userMapper.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                Role role1 = roleService.getById(role);
                if (ToolUtil.isNotEmpty(role1))
                    roleList.add(role1.getName());
            }
            map.put("roleList", roleList);
        } else {
            return ResponseData.error(Integer.valueOf(502), "查不到用户信息");
        }
        return ResponseData.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginVali(@RequestBody UserDto users,HttpServletResponse response){
        String username = users.getUsername();
        String password =  users.getPassword();

        if (ToolUtil.isOneEmpty(username, password)) {
            return ResponseData.error("账号或密码为空");
        }
        User user = userMapper.getByAccount(username);

        // 账号不存在
        if (null == user) {
            return ResponseData.error(1402, "账号密码错误");
        }

        //验证账号密码是否正确
        String requestMd5 = SaltUtil.md5Encrypt(password, user.getSalt());
        String dbMd5 = user.getPassword();
        if (dbMd5 == null || !dbMd5.equalsIgnoreCase(requestMd5)) {
            return ResponseData.error(1402, "账号密码错误");
        }
        // 账号被冻结
        if (!user.getStatus().equals(ManagerStatus.OK.getCode())) {
            return ResponseData.error(1404, "账号被冻结");
        }
        //登录并创建token
        String token = authService.login(username);
        //生成业务系统token
        //redisService.saveRedis(CacheKey.YWXTTOKENMAP,token,username);
        //request.getSession().setAttribute("token",token);
        return new SuccessResponseData(token);
    }

    /**
     * 美团列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfos list(BtyMtyqParam btyMtyqParam) {
        LayuiPageInfos list = mtyqService.findPageByList(btyMtyqParam);


        return list;
    }
    @ResponseBody
    @RequestMapping("/amount")
    public  ResponseData amount(BtyMtyqParam btyMtyqParam){
       BigDecimal amount= mtyqService.amount(btyMtyqParam);
        return ResponseData.success(amount);
    }

    /**
     * 美团详情
     */
    @ResponseBody
    @RequestMapping("/detail")
    public ResponseData detail(BtyMtyqParam btyMtyqParam) {
        String code = btyMtyqParam.getCode() == null ? "" : btyMtyqParam.getCode();
        BtyMtyq mt = mtyqService.getOne(new QueryWrapper<BtyMtyq>().eq("code", code));
        if (ToolUtil.isNotEmpty(mt)) {
            return ResponseData.success(mt);
        }
        return ResponseData.success();
    }

    /**
     * 美团验券{
     * "vendorOrderId": "412380809",
     * "toPayAmount": 28.00,
     * "orderSkus": [
     * {
     * "vendorSkuId": "2006141037019",
     * "vendorSkuName": "MayDay海鲜茄子煲1份",
     * "unit": "个",
     * "unitPrice": 0.1,
     * "count": 1
     * }
     * ],
     * "couponCode":
     * "77129208035668",
     * "vendorShopId": "957299785",
     * "eId": "5515951",
     * "eName": "收银员小明"
     * }
     */
    @PostMapping("/yq")
    @ResponseBody
    public ResponseData mtYq(HttpServletRequest request, @RequestBody MtYqParam mtYqParam) throws ParseException, NoSuchAlgorithmException {
        String ts = String.valueOf(System.currentTimeMillis());
        String version = "2.0";
        String algorithm = "SHA-1";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        String orderId = DateUtil.getStampNow();
        String couponCode = mtYqParam.getCouponCode();
        String vendorShopId = mtYqParam.getVendorShopId();
        String eId = mtYqParam.getEId();
        String eName = mtYqParam.getEName();
        MtYqParam.OrderSkusBean orderSkusBean = new MtYqParam.OrderSkusBean();
        List<MtYqParam.OrderSkusBean> listOrderSkusBean = mtYqParam.getOrderSkus();
        BigDecimal toPayAmounts = BigDecimal.ZERO;
        BigDecimal unitPrice = BigDecimal.ZERO;
        String date= DateUtil.getNowDate();
        String month=date.substring(0,7);
        for (MtYqParam.OrderSkusBean skusBean : listOrderSkusBean) {
            orderSkusBean.setVendorSkuId(skusBean.getVendorSkuId());
            orderSkusBean.setVendorSkuName(skusBean.getVendorSkuName());
            orderSkusBean.setUnit(skusBean.getUnit());
            unitPrice = skusBean.getUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
            toPayAmounts = toPayAmounts.add(unitPrice);
            orderSkusBean.setUnitPrice(unitPrice);
            orderSkusBean.setCount(mtYqParam.getOrderSkus().get(0).getCount());
        }

        List<MtYqParam.OrderSkusBean> list = new ArrayList<>();
        list.add(orderSkusBean);
        JSONObject json1 = new JSONObject();

        json1.put("vendorOrderId", orderId);
        json1.put("toPayAmount", toPayAmounts);
        json1.put("orderSkus", list);
        json1.put("couponCode", couponCode);
        json1.put("vendorShopId", vendorShopId);
        json1.put("eId", eId);
        json1.put("eName", eName);
        String fours = json1.toJSONString();
        String[] paramss = new String[]{"appKey"+appKey,"ts"+ts,"version"+version,fours};
        Arrays.sort(paramss);
        // 将5个参数字符串拼接成一个字符串进行sha1加密
        String clearTexts =appSecret+paramss[0]+paramss[1]+paramss[2]+paramss[3];
        String sign1 = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearTexts).getBytes()), true));
        System.out.println("sign:" + sign1);
        logger.info("sign:"+sign1);
        String url1 = "https://open-api.dianping.com/tuangou/coupon/matchConsume?version="+version+"&appKey="+appKey+"&ts="+ts+"&sign="+sign1;
        logger.info("url:" + url1);
        logger.info("json:" + json1);
        HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers);
        //String result = restTemplate.postForEntity(url1, formEntity1, String.class).getBody();
        MtYqResult mtYqResult = restTemplate.postForEntity(url1, formEntity1, MtYqResult.class).getBody();
        logger.info("result:" + mtYqResult.getCode());
        System.out.println("result1111:" + mtYqResult.getCode());
        if (mtYqResult.getCode() == 200) {
            BtyMtyq mtyq = new BtyMtyq();
            mtyq.setId(UUIDUtils.getId());
            //门店id
            mtyq.setMdid(vendorShopId);
            //957299785
            if(vendorShopId.equals("677392350")){
                mtyq.setDm("東更道点心行（文化东路店）");
            }else if(vendorShopId.equals("957299785")){
                mtyq.setDm("東更道点心行（印象城店）");
            }
            else {
                mtyq.setDm("东更道测试门店");
            }
            mtyq.setName(mtYqResult.getContent().getCouponCodeList().get(0).getDealTitle());
            mtyq.setType(mtYqResult.getContent().getCouponCodeList().get(0).getDealType());
            mtyq.setCode(couponCode);
            mtyq.setState(10);
            //实收金额realAmount
            //mtyq.setAmount(mtYqResult.getContent().getCouponCodeList().get(0).getRealAmount());
            mtyq.setAmount(mtYqResult.getContent().getTotalRealAmount());
            //抵扣金额dealCouponAmount
            mtyq.setDkje(mtYqResult.getContent().getCouponCodeList().get(0).getDealCouponAmount());
            //优惠金额discountAmount
            mtyq.setYhje(mtYqResult.getContent().getCouponCodeList().get(0).getDiscountAmount());
            mtyq.setCreateName(mtYqParam.getCreateName());
            mtyq.setCreatePhone(mtYqParam.getCreatePhone());
            mtyq.setMonth(month);
            mtyq.setCreateTime(new Date());
            mtyqService.save(mtyq);
            return ResponseData.success("验券成功！");
        } else {
            return ResponseData.error(mtYqResult.getCode(), mtYqResult.getMsg());
        }

    }

    /**
     * 美团撤销验券
     * {
     * "vendorShopId": "957299785",
     * "couponCode": "77129208035668",
     * "eId": "5515951",
     * "eName": "收银员小明"
     * }
     */
    @PostMapping("/cxYq")
    @ResponseBody
    public ResponseData cxYq(HttpServletRequest request, @RequestBody MtYqParam mtYqParam) throws Exception {

        String ts = String.valueOf(System.currentTimeMillis());
        String version = "2.0";
        JSONObject json = new JSONObject();
        String couponCode = mtYqParam.getCouponCode();
        String vendorShopId = mtYqParam.getVendorShopId();
        String eId = mtYqParam.getEId();
        String eName = mtYqParam.getEName();

        json.put("couponCode", couponCode);
        json.put("vendorShopId", vendorShopId);
        json.put("eId", eId);
        json.put("eName", eName);

        CouponCancelRequest cancelRequest=new CouponCancelRequest();
        cancelRequest.setCouponCode(couponCode);
        cancelRequest.setVendorShopId(vendorShopId);
        cancelRequest.setEId(eId);
        cancelRequest.setEName(eName);

        TuangouCouponCancelAPI api=new TuangouCouponCancelAPI();
        api.setRequest(cancelRequest);
        ApiClient client = new DefaultApiClient("4d0b1d035c651af830ecf9fc32ae69f24dc24ec6", "b47f94240f07d06be96167fc0c88f7ededb9ddb0");
        BasicResponseModel rsp = client.execute(api);

        if (rsp.getCode()==200) {
            //更新当前券的状态为已撤销
            BtyMtyq mtyq = mtyqService.getOne(new QueryWrapper<BtyMtyq>().eq("code", couponCode));
            if (ToolUtil.isNotEmpty(mtyq)) {
                mtyq.setState(25);
                mtyq.setUpdateTime(new Date());
                mtyqService.updateById(mtyq);
            }
            return ResponseData.success("撤销验券成功！");
        } else {
            return ResponseData.error(rsp.getCode()+rsp.getMsg());
        }

    }
    @GetMapping("/query")
    @ResponseBody
    public ResponseData query(BtyMtyqParam btyMtyqParam) throws Exception {
//        String ts = String.valueOf(System.currentTimeMillis());
//        String version = "2.0";
//        JSONObject json = new JSONObject();
        String couponCode=btyMtyqParam.getCode();
        String vendorShopId=btyMtyqParam.getVendorShopId();
//
//        json.put("couponCode", couponCode);
//        json.put("vendorShopId", vendorShopId);
//        String four = json.toJSONString();
//        String[] params = new String[]{"appKey"+appKey,"ts"+ts,"version"+version,four};
//        Arrays.sort(params);
//        // 将5个参数字符串拼接成一个字符串进行sha1加密
//        String clearText = appSecret+params[0]+params[1]+params[2]+params[3];
//        String algorithm = "SHA-1";
//        String sign = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
//        //System.out.println("sign:"+sign);
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//        headers.setContentType(type);
//        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
//        String url = "https://open-api.dianping.com/tuangou/coupon/status/query?version="+version+"&appKey="+appKey+"&ts="+ts+"&sign="+sign;
//        System.out.println("urls:"+url);
//        //String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
//        Mt mt= restTemplate.postForEntity(url, formEntity, Mt.class).getBody();
//        //System.out.println("result:"+result);
//        JsonParser jp = new JsonParser();
//        //将json字符串转化成json对象
//        //JsonObject jo = jp.parse(result).getAsJsonObject();
//        //获取code对应的值
//       // String code = jo.get("code").getAsString();

//        if(mt.getCode()==200){
//            Mt.ContentBean bean=mt.getContent();
//            return ResponseData.success(bean);
//        }else{
//            return ResponseData.error(mt.getCode(),mt.getMsg());
//        }
        CouponStatusQueryRequest request=new CouponStatusQueryRequest();
        request.setCouponCode(couponCode);
        request.setVendorShopId(vendorShopId);
        TuangouCouponStatusQueryAPI api=new TuangouCouponStatusQueryAPI();
        api.setRequest(request);
        ApiClient client = new DefaultApiClient(appKey, appSecret);
        BasicResponseModel rsp = client.execute(api);
        if(rsp.getCode() == 200){
            return ResponseData.success(rsp.getContent());
        }else{
            return ResponseData.error(rsp.getCode(),rsp.getMsg());
        }

    }
    @PostMapping("/yqs")
    @ResponseBody
    public ResponseData mtYqs( @RequestBody MtYqParam mtYqParam) throws Exception {
        String orderId = DateUtil.getStampNow();
        String couponCode = mtYqParam.getCouponCode();
        String vendorShopId = mtYqParam.getVendorShopId();
        String eId = mtYqParam.getEId();
        String eName = mtYqParam.getEName();

        List<OrderSkuDTO> lists=new ArrayList<>();
        OrderSkuDTO dto=new OrderSkuDTO();
        List<MtYqParam.OrderSkusBean> listOrderSkusBean = mtYqParam.getOrderSkus();
        BigDecimal toPayAmounts = BigDecimal.ZERO;
        BigDecimal unitPrice = BigDecimal.ZERO;
        String date= DateUtil.getNowDate();
        String month=date.substring(0,7);
        for (MtYqParam.OrderSkusBean skusBean : listOrderSkusBean) {
            unitPrice = skusBean.getUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
            toPayAmounts = toPayAmounts.add(unitPrice);
            dto.setVendorSkuId(skusBean.getVendorSkuId());
            dto.setVendorSkuName(skusBean.getVendorSkuName());
            dto.setUnit("个");
            dto.setUnitPrice(unitPrice);
            dto.setCount(1);
            lists.add(dto);
        }
        TuangouMatchConsumeRequest request=new TuangouMatchConsumeRequest();

        request.setOrderSkus(lists);
        request.setVendorOrderId(orderId);
        request.setToPayAmount(toPayAmounts);
        request.setCouponCode(couponCode);
        request.setVendorShopId(vendorShopId);
        request.setEId(eId);
        request.setEName(eName);
        TuangouCouponMatchConsumeAPI api=new TuangouCouponMatchConsumeAPI();
        api.setRequest(request);
        ApiClient client = new DefaultApiClient("4d0b1d035c651af830ecf9fc32ae69f24dc24ec6", "b47f94240f07d06be96167fc0c88f7ededb9ddb0");
        BasicResponseModel rsp = client.execute(api);
        String result=JSON.toJSONString(rsp);
        System.out.println("result:"+JSON.toJSONString(rsp));
        System.out.println("code:"+rsp.getCode()+rsp.getMsg());
        if (rsp.getCode() == 200) {
            BtyMtyq mtyq = new BtyMtyq();
            mtyq.setId(UUIDUtils.getId());
            //门店id
            mtyq.setMdid(vendorShopId);
            //1736714923
            if(vendorShopId.equals("677392350")){
                mtyq.setDm("東更道点心行（文化东路店）");
            }else if(vendorShopId.equals("957299785")){
                mtyq.setDm("東更道点心行（印象城店）");
            }else if(vendorShopId.equals("1736714923")){
                mtyq.setDm("東更道点心行（花园路店）");
            }
            else {
                mtyq.setDm("东更道测试门店");
            }
            MtYqResult response=  JSONObject.parseObject(result,MtYqResult.class);
            mtyq.setName(response.getContent().getCouponCodeList().get(0).getDealTitle());
            mtyq.setType(response.getContent().getCouponCodeList().get(0).getDealType());
            mtyq.setCode(couponCode);
            mtyq.setState(10);
            //实收金额realAmount
            //mtyq.setAmount(mtYqResult.getContent().getCouponCodeList().get(0).getRealAmount());
            mtyq.setAmount(response.getContent().getTotalRealAmount());
            //抵扣金额dealCouponAmount
            mtyq.setDkje(response.getContent().getCouponCodeList().get(0).getDealCouponAmount());
            //优惠金额discountAmount
            mtyq.setYhje(response.getContent().getCouponCodeList().get(0).getDiscountAmount());
            mtyq.setCreateName(mtYqParam.getCreateName());
            mtyq.setCreatePhone(mtYqParam.getCreatePhone());
            mtyq.setMonth(month);
            mtyq.setCreateTime(new Date());
            mtyqService.save(mtyq);
            return ResponseData.success("验券成功！");
        } else {
            return ResponseData.error(rsp.getCode(), rsp.getMsg());
        }

    }

    @PostMapping("/queryByPage")
    @ResponseBody
    public ResponseData queryByPage( @RequestBody HttpServletRequest req) throws Exception {
        TradePageQueryRequest request=new TradePageQueryRequest();
        Date date=DateUtil.getDateByStr(req.getParameter("date"));
        request.setDate(date);
        request.setLimit(500);
        request.setOffset(0);
        TuangouTradeQueryByPageAPI api=new TuangouTradeQueryByPageAPI();
        api.setRequest(request);
        ApiClient client = new DefaultApiClient("4d0b1d035c651af830ecf9fc32ae69f24dc24ec6", "b47f94240f07d06be96167fc0c88f7ededb9ddb0");
        BasicResponseModel rsp = client.execute(api);
        String result=JSON.toJSONString(rsp);
        System.out.println("result:"+JSON.toJSONString(rsp));

        return  ResponseData.success();
    }

}
